//
//  JoinViewController.swift
//  Liao
//
//  Created by 范东 on 2022/3/17.
//

import UIKit
import FDUIKit

class JoinViewController: BaseViewController {
    
    var type = CallType.voiceCall
    
    let margin: CGFloat = 15
    
    var fromUser = V2TIMGroupMemberFullInfo()
    var channelId = ""
    
    var audioPlayer: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupCallAudio()
        setupViews()
        setupData()
        if type == .videoCall {
            statusLabel.text = NSLocalizedString("VideoInvite", comment: "")
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        audioPlayer?.stop()
        audioPlayer = nil
    }
    
    func setupViews(){
        view.addSubview(bgImageView)
        bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        view.addSubview(visualView)
        visualView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        view.addSubview(shadowView)
        view.addSubview(iconImageView)
        view.addSubview(nameLabel)
        view.addSubview(statusLabel)
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        iconImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(CGFloat.topHeight)
            make.size.equalTo(CGSize(width: 100, height: 100))
            make.centerX.equalToSuperview()
        }
        nameLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.iconImageView.snp.bottom).offset(30)
        }
        statusLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(self.nameLabel.snp.bottom).offset(10)
        }
        
        
        view.addSubview(acceptBtn)
        acceptBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(84)
            make.bottom.equalToSuperview().offset(-CGFloat.safeAreaBottomHeight-self.margin)
            make.size.equalTo(CGSize(width: 64, height: 90))
        }
        view.addSubview(refuseBtn)
        refuseBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-84)
            make.bottom.equalToSuperview().offset(-CGFloat.safeAreaBottomHeight-self.margin)
            make.size.equalTo(CGSize(width: 64, height: 90))
        }
    }
    
    func setupData(){
        bgImageView.sd_setImage(with: URL(string: fromUser.faceURL), placeholderImage: .iconPlaceHolderImage)
        iconImageView.sd_setImage(with: URL(string: fromUser.faceURL), placeholderImage: .iconPlaceHolderImage)
        nameLabel.text = fromUser.nickName
    }
    
    func setupCallAudio(){
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "calling", ofType: "mp3")!))
            audioPlayer?.numberOfLoops = -1
            audioPlayer?.play()
        } catch let error {
            debugPrint(error.localizedDescription)
        }
    }
    
    @objc func acceptBtnAction(sender: UIButton){
        let messageModel = MessageModel()
        messageModel.type = MessageType.callAccept.rawValue
        if type == .videoCall {
            messageModel.desc = NSLocalizedString("Accept a video call", comment: "")
        }else{
            messageModel.desc = NSLocalizedString("Accept a voice call", comment: "")
        }
        
        IMManager.send(toUserId: fromUser.userID, message: messageModel) { result in
            //进入通话界面
            let callVC = VideoCallViewController()
            callVC.channelId = self.channelId
            callVC.fromUser = self.fromUser
            callVC.type = self.type
            callVC.modalPresentationStyle = .fullScreen
            self.dismiss(animated: true, completion: nil)
            FMRadio.shared.tabC?.callVC = callVC
            FMRadio.shared.tabC?.present(callVC, animated: true, completion: nil)
        } failure: { error in
            self.view.makeToast(error)
        }
    }
    
    @objc func refuseBtnAction(sender: UIButton){
        let messageModel = MessageModel()
        messageModel.type = MessageType.callRefuse.rawValue
        if type == .videoCall {
            messageModel.desc = NSLocalizedString("Refuse a video call", comment: "")
        }else{
            messageModel.desc = NSLocalizedString("Refuse a voice call", comment: "")
        }
        IMManager.send(toUserId: fromUser.userID, message: messageModel) { result in
            debugPrint("拒绝了通话")
            self.dismiss(animated: true, completion: nil)
        } failure: { error in
            self.view.makeToast(error)
        }
    }
    
    lazy var bgImageView: UIImageView = {
        let bgImageView = UIImageView(frame: .zero)
        bgImageView.contentMode = .scaleAspectFill
        bgImageView.clipsToBounds = true
        return bgImageView
    }()
    
    lazy var visualView: UIVisualEffectView = {
        let visualView = UIVisualEffectView(effect: UIBlurEffect.qmui_effect(withBlurRadius: 10))
        return visualView
    }()
    
    lazy var shadowView: UIView = {
        let shadowView = UIView(frame: .zero)
        shadowView.backgroundColor = .black.withAlphaComponent(0.5)
        return shadowView
    }()
    
    lazy var nameLabel: UILabel = {
        let timeLabel = UILabel(frame: .zero)
        timeLabel.textColor = .systemBackground
        timeLabel.font = .systemFont(ofSize: 20, weight: .medium)
        return timeLabel
    }()
    
    lazy var iconImageView: UIImageView = {
        let bgImageView = UIImageView(frame: .zero)
        bgImageView.contentMode = .scaleAspectFill
        bgImageView.clipsToBounds = true
        bgImageView.layer.cornerRadius = 10
        return bgImageView
    }()
    
    lazy var statusLabel: UILabel = {
        let timeLabel = UILabel(frame: .zero)
        timeLabel.textColor = .systemGray3
        timeLabel.font = .systemFont(ofSize: 15)
        timeLabel.text = NSLocalizedString("VoiceInvite", comment: "")
        return timeLabel
    }()
    
    lazy var acceptBtn: QMUIButton = {
        let acceptBtn = QMUIButton(type: .custom)
        acceptBtn.setImage(UIImage(named: "icon_call"), for: .normal)
        acceptBtn.setTitle(NSLocalizedString("Accept", comment: ""), for: .normal)
        acceptBtn.imagePosition = .top
        acceptBtn.spacingBetweenImageAndTitle = 10
        acceptBtn.setTitleColor(.systemGray, for: .normal)
        acceptBtn.titleLabel?.font = .systemFont(ofSize: 14)
        acceptBtn.addTarget(self, action: #selector(acceptBtnAction(sender:)), for: .touchUpInside)
        return acceptBtn
    }()
    
    lazy var refuseBtn: QMUIButton = {
        let refuseBtn = QMUIButton(type: .custom)
        refuseBtn.setImage(UIImage(named: "icon_hangup"), for: .normal)
        refuseBtn.setTitle(NSLocalizedString("Refuse", comment: ""), for: .normal)
        refuseBtn.imagePosition = .top
        refuseBtn.spacingBetweenImageAndTitle = 10
        refuseBtn.setTitleColor(.systemGray, for: .normal)
        refuseBtn.titleLabel?.font = .systemFont(ofSize: 14)
        refuseBtn.addTarget(self, action: #selector(refuseBtnAction(sender:)), for: .touchUpInside)
        return refuseBtn
    }()
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        .lightContent
    }

}
